package com.yicong.ants.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import android.widget.Toast;

import com.yicong.ants.Constants;

import java.util.List;

public class PermissionsChecker {

    /**
     * 检查是否有尚未获取权限
     * true 有权限
     * false 没有权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkPermissions(Context context, String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (null == context || null == permissions || permissions.length <= 0) {
            return false;
        }
        boolean value = true;
        for (String permission : permissions) {
            if (lacksPermission(context, permission)) {
                value = false;
                break;
            }
        }
        return value;
    }

    public static boolean checkInstallPermission(Activity activity) {
        boolean haveInstallPermission = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = activity.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                ToastUtils.show(activity, "安装应用需要打开未知来源权限，请去设置中开启权限", Toast.LENGTH_LONG);
                startInstallPermissionSettingActivity(activity);
                return false;
            }
        }
        return haveInstallPermission;
    }

    private static void startInstallPermissionSettingActivity(Activity activity) {
        Uri packageURI = Uri.parse("package:" + activity.getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        activity.startActivityForResult(intent, Constants.Req_Code.Install_App_Permission);
    }

    /**
     * 查看当前权限是否被拒绝
     *
     * @param context
     * @param permission
     * @return
     */
    private static boolean lacksPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission)
            == PackageManager.PERMISSION_DENIED;
    }

    public static abstract class PermissionsCallBack {
        public abstract void PermissionsSuccess();

        public void PermissionsFailed(int requestCode, @NonNull List<String> permissions) {
        }

        ;
    }
}
